<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="投保人名称" prop="toubaoId">
        <el-select v-model="queryParams.toubaoId" placeholder="请选择投保人名称" clearable>
          <el-option
              v-for="dict in taobaoList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="被保险人名称" prop="beibaoId">
        <el-select v-model="queryParams.beibaoId" placeholder="请选择被保险人名称" clearable>
          <el-option
              v-for="dict in taobaoList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="保险人名称" prop="baoxianId">
        <el-select v-model="queryParams.baoxianId" placeholder="请选择保险人名称" clearable>
          <el-option
              v-for="dict in baoxianList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经纪/代理公司名称" prop="proxyId" label-width="130px">
        <el-select v-model="queryParams.proxyId" placeholder="请选择经纪/代理公司名称" clearable>
          <el-option
              v-for="dict in proxyList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="险种" prop="insureType" label-width="50">
        <el-select v-model="queryParams.insureType" placeholder="险种" clearable>
          <el-option
              v-for="dict in dict.type.insure_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['risk:contract:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['risk:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="warning"-->
      <!--    plain-->
      <!--    icon="el-icon-download"-->
      <!--    size="mini"-->
      <!--    @click="handleExport"-->
      <!--    v-hasPermi="['risk:contract:export']"-->
      <!--  >导出</el-button>-->
      <!--</el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="合同名称" align="center" prop="contractName"/>
      <el-table-column label="保单号码" align="center" prop="insureNo"/>
      <el-table-column label="风控及技术服务金额(元)" align="center" prop="riskAmount"/>
      <el-table-column label="计划金额" align="center" prop="riskAmountPlan"/>
      <el-table-column label="已收" align="center" prop="riskAmountReal"/>
      <el-table-column label="未收" align="center" prop="riskAmountNot"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="230">
        <template slot-scope="scope">
          <el-button
              v-if="!scope.row.id"
              type="text"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd(scope.row)"
              v-hasPermi="['risk:contract:add']"
          >新增
          </el-button>
          <el-button
              v-if="scope.row.id"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['risk:contract:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              v-if="scope.row.id"
              type="text"
              @click="gotToPay(scope.row)"
          >风控支付信息
          </el-button>
          <el-button
              v-if="scope.row.id"
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color: red"
              @click="handleDelete(scope.row)"
              v-hasPermi="['risk:contract:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改保险风控合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-card shadow="never" :body-style="{ height: '10px' }" :style="{
      'margin-bottom': '10px','height': '120px'
    }">
          <el-descriptions title="经纪/代理信息"/>
          <el-form-item label="风控及技术服务金额" prop="riskAmount">
            <el-input v-model="form.riskAmount" placeholder="请输入风控及技术服务金额"/>
          </el-form-item>
        </el-card>
        <el-card shadow="never" :body-style="{ height: '10px' }"
                 :style="{      'margin-bottom': '10px','height': tableHeight    }">
          <el-descriptions title="附件信息">
            <template slot="extra">
              <cus-file-upload :file-size="99999" :file-type="['pdf']"
                               @uploadSuccess="uploadSuccess" :limit="9999"></cus-file-upload>
            </template>
          </el-descriptions>
          <el-table v-loading="loading" :data="attachmentList" :max-height="tableHeight1" :key="tableKey">
            <el-table-column label="文件名称" align="center" prop="fileName">
              <template slot-scope="scope">
                <el-link type="primary" :href="`${baseUrl}/${scope.row.filePath}`" :underline="false" target="_blank">
                  {{ scope.row.fileName }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column label="上传人" align="center" prop="createBy">
              <template slot-scope="scope">
                {{ scope.row.id ? scope.row.createBy : scope.row.userName }}
              </template>
            </el-table-column>
            <el-table-column label="上传时间" align="center" prop="uploadDate" width="180">
              <template slot-scope="scope">
                <span>{{
                    parseTime(scope.row.id ? scope.row.uploadTime : scope.row.uploadDate, '{y}-{m}-{d} {h}:{m}:{s}')
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column label="文件类型" align="center" prop="fileType"/>
            <!--<el-table-column label="文件大小" align="center" prop="fileSize"/>-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleView(scope.row)"
                >预览
                </el-button>
                <el-button
                    size="mini"
                    type="text"
                    style="color: red"
                    icon="el-icon-delete"
                    @click="handleDeleteFile(scope.row)"
                    v-hasPermi="['risk:contract:edit']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listContract, getContract, delContract, addContract, updateContract} from "@/api/risk/contract";
import {getBaoxianlist, getDaililist, getToubaolist} from "@/api/common/common";
import {isEmpty, isValidAmount} from "@/utils/validate";
import CusFileUpload from "@/components/CusFileUpload/index.vue";
import dayjs from '@/utils/dayjs.min'

export default {
  name: "Contract",
  components: {CusFileUpload},
  dicts: ['insure_type'],
  data() {
    const checkPlanAmount = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (!isValidAmount(value)) {
        callback(new Error('请输入正确的金额'));
        return;
      }
      callback();
    }
    return {
      baoxianList: [],
      taobaoList: [],
      beibaoList: [],
      proxyList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      tableHeight: 0,
      tableHeight1: 0,
      tableKey: new Date().getTime(),
      // 保险附件表格数据
      attachmentList: [],
      touBaoList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保险风控合同表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        insureId: null,
        contractId: null,
        riskAmount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        riskAmount: [
          {required: true, message: "风控及技术服务金额不能为空", trigger: "blur"},
          {validator: checkPlanAmount, trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      let tableHeight = (window.innerHeight - 100) / 2
      this.tableHeight1 = tableHeight - 90
      this.tableHeight = tableHeight + 'px'
    })
  },
  created() {
    this.initData()
    this.getList();
  },
  methods: {

    /**
     * '{"fileName":"未命名1.pdf","fileExt":"pdf","fileType":"pdf","filePath":"bfiles/09d0697ed3824398ac22cbb1b2c95349/b22bfe83-4b8f-4b06-ab08-ccc8bcb77f9f.pdf","userName":"admin","uploadDate":"2024-11-25T16:04:17.753+08:00"}'
     * @param item
     */
    uploadSuccess(item) {
      this.attachmentList.push(item.data)
    },
    gotToPay(row) {
      this.$router.push(
          {
            path: '/views/risk/plan/index',
            query: {
              'insureId': row.insureId,
              'contractId': row.contractId,
              'riskId': row.id
            }
          }
      );
    },
    initData() {
      // getToubaolist().then().then(res => {
      //   res.data.forEach(item => {
      //     item.deptId = String(item.deptId)
      //   });
      //   this.touBaoList = res.data
      // })
      getToubaolist().then().then(res => {
        this.taobaoList = res.data
      })
      getBaoxianlist().then().then(res => {
        this.baoxianList = res.data
      })
      getDaililist().then().then(res => {
        this.proxyList = res.data
      })
    },
    /** 查询保险风控合同列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        insureId: null,
        contractId: null,
        riskAmount: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.insureId = row.insureId
      this.form.contractId = row.contractId
      this.attachmentList = []
      this.open = true;
      this.title = "添加保险风控合同";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.attachmentList = []
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.attachmentList = response.data.tbInsuranceAttachmentList
        console.log(this.attachmentList)
        this.open = true;
        this.title = "修改保险风控合同";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tbInsuranceAttachmentList = []
          if (!isEmpty(this.attachmentList)) {
            this.attachmentList.forEach(item => {
              item['uploadUserId'] = item.userName
              item['uploadTime'] = dayjs(item.uploadDate).format('YYYY-MM-DD HH:mm:ss')
              this.form.tbInsuranceAttachmentList.push(item)
            })
          }
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.id = undefined
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleView(row) {
      window.open(this.baseUrl+"/"+row.filePath, '_blank')
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险风控合同？').then(function () {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDeleteFile(row) {
      const _this = this
      this.$modal.confirm('是否确认删除选中的附件信息？').then(function () {
        // 本地删除
        let delIndex = _this.attachmentList.findIndex(item => item.filePath === row.filePath)
        _this.attachmentList.splice(delIndex, 1)
        _this.tableKey = new Date().getTime()
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('risk/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-descriptions {
  &:not(:nth-child(1)) {
    margin-top: 20px;
  }

  .el-descriptions__title {
    display: flex;
    align-items: center;

    &::before {
      display: inline-block;
      width: 3px;
      height: 20px;
      margin-right: 10px;
      background-color: #409eff;
      content: '';
    }
  }

  .el-descriptions-item__container {
    margin: 0 10px;

    .no-colon {
      margin: 0;

      &::after {
        content: '';
      }
    }
  }
}
</style>
